package com.example.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.config.JwtTokenUtil;
import com.example.springboot.service.AuthService;
import com.example.springboot.dto.AuthRequestDTO;
import com.example.springboot.dto.ResetPasswordRequestDTO;
import com.example.springboot.entity.Admin;
import com.example.springboot.entity.User;
import com.example.springboot.entity.Merchant;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/loginOrRegister")
    @ApiOperation("登陆注册")
    public ResponseEntity<?> loginOrRegister(@RequestBody AuthRequestDTO authRequest) {
        try {
            // 获取请求参数
            String identifier = authRequest.getPhoneNumber(); // 对于管理员是用户名
            String password = authRequest.getPassword();
            String role = authRequest.getRole();

            // 根据角色进行校验
            if (!"ADMIN".equalsIgnoreCase(role)) {
                // 校验手机号格式是否正确（仅适用于用户和商家）
                if (!isValidPhoneNumber(identifier)) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("手机号格式不正确");
                }
                // 校验密码是否为空
                if (password == null || password.trim().isEmpty()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("密码不能为空");
                }
            } else {
                // 对于管理员，用户名不能为空
                if (identifier == null || identifier.trim().isEmpty()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("管理员用户名不能为空");
                }
                // 校验密码是否为空
                if (password == null || password.trim().isEmpty()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("密码不能为空");
                }
            }

            // 调用登录或注册逻辑
            Object response = authService.loginOrRegister(identifier, password, role);

            // 根据不同的角色返回不同的响应
            if (response instanceof Admin) {
                Admin admin = (Admin) response;
                String token = jwtTokenUtil.generateToken(admin.getUsername(), "ADMIN");

                Map<String, Object> responseBody = new HashMap<>();
                responseBody.put("token", token);
                responseBody.put("user", admin);

                return ResponseEntity.ok(responseBody);
            } else if (response instanceof User) {
                User user = (User) response;
                // 使用新方法生成 token，包含 realUserId
                String token = jwtTokenUtil.generateToken(user.getUsername(), "USER", String.valueOf(user.getUserId()));

                Map<String, Object> responseBody = new HashMap<>();
                responseBody.put("token", token);
                responseBody.put("user", user);

                return ResponseEntity.ok(responseBody);
            } else if (response instanceof Merchant) {
                Merchant merchant = (Merchant) response;
                String token = jwtTokenUtil.generateToken(merchant.getName(), "MERCHANT");

                Map<String, Object> responseBody = new HashMap<>();
                responseBody.put("token", token);
                responseBody.put("user", merchant);

                return ResponseEntity.ok(responseBody);
            }

            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的角色类型");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }

    // 验证手机号是否合法，仅适用于商家和用户
    private boolean isValidPhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        return phoneNumber != null && phoneNumber.matches(regex);
    }

    // 发送密码重置码
    @PostMapping("/forgotPassword")
    @ApiOperation("验证手机号并发送密码重置码")
    public ResponseEntity<?> forgotPassword(@RequestParam String phoneNumber,
                                            @RequestParam String role) {
        try {
            return ResponseEntity.ok(authService.sendPasswordResetCode(phoneNumber, role));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("服务器内部错误: " + e.getMessage());
        }
    }

    // 重置密码
    @PostMapping("/resetPassword")
    @ApiOperation("重置密码")
    public ResponseEntity<?> resetPassword(@RequestBody ResetPasswordRequestDTO resetPasswordRequest) {
        try {
            return ResponseEntity.ok(authService.resetPassword(
                    resetPasswordRequest.getPhoneNumber(),
                    resetPasswordRequest.getRole(),
                    resetPasswordRequest.getVerificationCode(),
                    resetPasswordRequest.getNewPassword()
            ));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("服务器内部错误: " + e.getMessage());
        }
    }
}